//
//  SXWeatherViewController.m
//  ShiXun
//
//  Created by lanou on 15/11/4.
//  Copyright © 2015年 张琪. All rights reserved.
//

#define key @"&key=84cdd5bcc0c9aaa2929873ac5e7ae52c"

#import "SXWeatherViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "SXRequestManager.h"
#import "SXWeatherModel.h"
#import "SXWeatherMoreTableViewController.h"
#import "SXWeatherIndexTableViewController.h"
#import "UIView+UIView.h"
#import "SXRefreshView.h"

@interface SXWeatherViewController () <CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager *locationManager;

@property (nonatomic, strong) SXWeatherModel *weatherModel;
@property (nonatomic, strong) UIView *weatherView;
@property (nonatomic, strong) SXWeatherMoreTableViewController *moreVC;
@property (nonatomic, strong) SXWeatherIndexTableViewController *indexVC;
@property (nonatomic, strong) SXRefreshView *refreshingView;

@end

@implementation SXWeatherViewController

- (void)setCityString:(NSString *)cityString
{
    _cityString = [cityString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self requestData];
}

- (UIView *)weatherView
{
    if (!_weatherView) {
        _weatherView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight - 274)];
        
        UILabel *temLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, kScreenWidth / 2, 50)];
        temLabel.text = [NSString stringWithFormat:@"%@°", _weatherModel.temperature];
        temLabel.font = [UIFont systemFontOfSize:25];
        [_weatherView addSubview:temLabel];
        
        UILabel *infoLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 60, kScreenWidth / 2, 30)];
        infoLabel.font = [UIFont systemFontOfSize:18];
        infoLabel.text = [NSString stringWithFormat:@"%@", _weatherModel.info];
        [_weatherView addSubview:infoLabel];
        
        UILabel *windLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, kScreenWidth / 2, 30)];
        windLabel.text = [NSString stringWithFormat:@"%@,%@", _weatherModel.direct, _weatherModel.power];
        windLabel.font = [UIFont systemFontOfSize:18];
        [_weatherView addSubview:windLabel];
        
        UILabel *cityLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, _weatherView.height - 90, kScreenWidth / 2, 30)];
        cityLabel.text = _weatherModel.cityName;
        cityLabel.font = [UIFont systemFontOfSize:15];
        [_weatherView addSubview:cityLabel];
        
        UILabel *timeLabe = [[UILabel alloc] initWithFrame:CGRectMake(20, _weatherView.height - 60, kScreenWidth / 2, 30)];
        timeLabe.font = [UIFont systemFontOfSize:15];
        NSString *date = [(SXWeatherMoreModel *)_weatherModel.moreArray[0] date];
        timeLabe.text = [NSString stringWithFormat:@"%@ %@ 发布", [date substringFromIndex:5], _weatherModel.time];
        [_weatherView addSubview:timeLabe];
        
        UIButton *button = [UIButton buttonWithType:(UIButtonTypeSystem)];
        button.frame = CGRectMake(kScreenWidth - 70, timeLabe.y, 60, 30);
        [button setTitle:@"生活指数" forState:(UIControlStateNormal)];
        [button addTarget:self action:@selector(chuanyi) forControlEvents:(UIControlEventTouchUpInside)];
        [_weatherView addSubview:button];
    }
    return _weatherView;
}

- (SXWeatherMoreTableViewController *)moreVC
{
    if (!_moreVC) {
        _moreVC = [[SXWeatherMoreTableViewController alloc] init];
        _moreVC.dataArray = _weatherModel.moreArray;
        _moreVC.view.frame = CGRectMake(0, kScreenHeight - 180, kScreenWidth, 180);
    }
    return _moreVC;
}

- (SXWeatherIndexTableViewController *)indexVC
{
    if (!_indexVC) {
        _indexVC = [[SXWeatherIndexTableViewController alloc] init];
        _indexVC.dataArray = _weatherModel.indexArray;
        _indexVC.view.frame = CGRectMake(0, kScreenHeight, kScreenWidth, 210);
    }
    return _indexVC;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.hidden = NO;
    self.navigationItem.title = @"时讯天气";
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self addLocation];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    imageView.image = [UIImage imageNamed:@"SX-tianqi"];
    imageView.userInteractionEnabled = YES;
    [self.view addSubview:imageView];
 
    _refreshingView = [[SXRefreshView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:_refreshingView];
}

// 网络请求
- (void)requestData
{
    NSString *urlString = [[kWeatherURlString stringByAppendingString:_cityString] stringByAppendingString:key];
    [SXRequestManager requestWithType:GET urlString:urlString parDic:nil finish:^(NSData *data) {
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers) error:nil];
        NSDictionary *dic = dict[@"result"][@"data"];
        _weatherModel = [[SXWeatherModel alloc] init];
        [_weatherModel setValuesForKeysWithDictionary:dic];
        [_refreshingView removeFromSuperview];
        [self.view addSubview:self.moreVC.view];
        [self.view addSubview:self.indexVC.view];
        [self.view addSubview:self.weatherView];
    } error:^(NSError *error) {
        NSLog(@"%@", error);
    }];
    
}

// 开始定位
- (void)addLocation
{
    _locationManager = [[CLLocationManager alloc] init];
    if (![CLLocationManager locationServicesEnabled]) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"设备未打开定位功能，将不能获取您所在位置的天气" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil];
        [alertView show];
        self.cityString = @"北京市";
        return;
    }
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
        [_locationManager requestWhenInUseAuthorization];
    }
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse)
    {
        _locationManager.delegate = self;
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        [_locationManager startUpdatingLocation];
    }
}

// 定位后
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    CLLocation *location = [locations firstObject];
    [manager stopUpdatingLocation];
    
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (placemarks.count > 0) {
            CLPlacemark *placemark = [placemarks objectAtIndex:0];
            NSString *city = placemark.locality;
            if (!city) {
                city = placemark.administrativeArea;
            }
            self.cityString = city;
        }
    }];
    
}

- (void)chuanyi
{
    if (self.indexVC.view.y == kScreenHeight) {
        [UIView animateWithDuration:0.5 animations:^{
            self.indexVC.view.y = kScreenHeight - 210;
        }];
    }
    else
    {
        [UIView animateWithDuration:0.5 animations:^{
            self.indexVC.view.y = kScreenHeight;
        }];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
